package com.qingjiang.projectschedule.interceptor;

import com.qingjiang.projectschedule.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginProtectedInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equals(request.getMethod().toUpperCase())) {
            return true;
        }
        String token = request.getHeader("token");
        if (token == null || jwtUtil.isExpiration(token) || !jwtUtil.verifyToken(token)) {
            response.setContentType("text/plain"); // 设置响应内容类型为纯文本
            response.setCharacterEncoding("UTF-8");
            response.setStatus(401);
            response.getWriter().print("请重新登录！");
            response.getWriter().flush();
            return false;
        }
        return true;
    }
}
